package gazzera.swing;

import gazzera.gui.messages.*;
import gazzera.swing.components.*;
import gazzera.swing.components.Box;
import gazzera.swing.model.*;
import gazzera.swing.utility.*;
import gazzera.utils.*;

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;

import javax.swing.*;

public class PeerPropertiesFolderWindow extends JFrame implements ActionListener
{
	private final Gazzera gazzera;
	private final Connection connection;
	private Map<String, JCheckBox> cbs;
	private final JTextField newgroup;

	public PeerPropertiesFolderWindow(final Gazzera gazzera, Connection connection) throws HeadlessException
	{
		super();
		
		setTitle("Properties");
		
		this.connection = connection;
		this.gazzera = gazzera;
		setSize(300, 300);
		setIconImage(new ImageIcon(ResourceLoader.get("icon.png")).getImage());
		setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
		
		Box b = new Box(true);
		
		
		Panel data = new Panel(new GridLayout(4, 2));
		data.add(new JLabel("Nickname"));
		data.add(new JLabel(connection.nickname));

		data.add(new JLabel("Hash"));
		data.add(new JLabel(connection.hash));

		data.add(new JLabel("Last addr"));
		data.add(new JLabel(connection.host+":"+connection.port));

		data.add(new JLabel("Status"));
		data.add(new JLabel(connection.status.toString()));

		b.add(data, false);
		
		
		JLabel banner2 = new JLabel("Groups assigned to this person:");
		banner2.setMinimumSize(new Dimension(10, 20));
		b.add(banner2, false);
		
		JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT));
		
		
		
		cbs = new HashMap<String,JCheckBox>(); 
		for (String g : gazzera.allGroups)
		{
			JCheckBox j1 = new JCheckBox(g);
			j1.setSelected(connection.groups.contains(g));
			cbs.put(g, j1);
			p.add(j1);
		}
		newgroup = new HintTextField("Enter new group");
		newgroup.setColumns(15);
		p.add(newgroup);
						
		b.add(p, true);
		
		JPanel p2 = new JPanel(new FlowLayout(FlowLayout.RIGHT));
		JButton cancel = new JButton("Cancel");
		cancel.addActionListener(new ActionListener()
		{
			@Override
			public void actionPerformed(ActionEvent e)
			{
				PeerPropertiesFolderWindow.this.dispose();
				
			}
		});
		p2.add(cancel);
		JButton ok = new JButton("Ok");
		ok.addActionListener(this);
		p2.add(ok);
		b.add(p2, false);
		add(b);
	}

	@Override
	public void actionPerformed(ActionEvent e)
	{
		// clicked ok!
		
		List<String> groups = new ArrayList<String>();
		for (String group : cbs.keySet())
		{
			JCheckBox x = cbs.get(group);
			if (x.isSelected())
			{
				groups.add(group);
			}
		}
		if(!Str.isEmpty(newgroup.getText()))
		{
			String ng = Str.strip(newgroup.getText().trim());
			groups.add(ng);
			gazzera.allGroups.add(ng);
		}
		gazzera.gui.pass(new ChangeNodeGroups(connection.hash, groups));
		
		this.dispose();
		
	}

	
	
	

}
